package com.luom.fsp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luom.fsp.annotation.AuthCheck;
import com.luom.fsp.common.BaseResponse;
import com.luom.fsp.common.DeleteRequest;
import com.luom.fsp.common.ErrorCode;
import com.luom.fsp.common.ResultUtils;
import com.luom.fsp.constant.UserConstant;
import com.luom.fsp.exception.BusinessException;
import com.luom.fsp.exception.ThrowUtils;
import com.luom.fsp.model.dto.coupon.CouponAddRequest;
import com.luom.fsp.model.dto.coupon.CouponQueryRequest;
import com.luom.fsp.model.dto.coupon.CouponUpdateRequest;
import com.luom.fsp.model.dto.userCoupon.UserCouponQueryRequest;
import com.luom.fsp.model.entity.Coupon;
import com.luom.fsp.model.entity.User;
import com.luom.fsp.model.entity.UserCoupon;
import com.luom.fsp.model.vo.CouponVO;
import com.luom.fsp.model.vo.UserCouponVO;
import com.luom.fsp.service.CouponService;
import com.luom.fsp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;

/**
 * 优惠券接口
 *
*/
@RestController
@RequestMapping("/coupon")
@Slf4j
public class CouponController {

    @Resource
    private CouponService couponService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建优惠券
     *
     * @param couponAddRequest
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addCoupon(@RequestBody CouponAddRequest couponAddRequest) {
        ThrowUtils.throwIf(couponAddRequest == null, ErrorCode.PARAMS_ERROR);
        Coupon coupon = new Coupon();
        BeanUtils.copyProperties(couponAddRequest, coupon);
        long newCouponId =couponService.addCoupon(coupon);
        return ResultUtils.success(newCouponId);
    }

    /**
     * 删除优惠券
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteCoupon(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Coupon oldCoupon = couponService.getById(id);
        ThrowUtils.throwIf(oldCoupon == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅管理员可删除
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = couponService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新优惠券（仅管理员可用）
     *
     * @param couponUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateCoupon(@RequestBody CouponUpdateRequest couponUpdateRequest) {
        if (couponUpdateRequest == null || couponUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Coupon coupon = new Coupon();
        BeanUtils.copyProperties(couponUpdateRequest, coupon);
        // 数据校验
        couponService.validCoupon(coupon, false);
        // 判断是否存在
        long id = couponUpdateRequest.getId();
        Coupon oldCoupon = couponService.getById(id);
        ThrowUtils.throwIf(oldCoupon == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = couponService.updateById(coupon);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取优惠券（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CouponVO> getCouponVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Coupon coupon = couponService.getById(id);
        ThrowUtils.throwIf(coupon == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(couponService.getCouponVO(coupon, request));
    }

    /**
     * 分页获取优惠券列表（仅管理员可用）
     *
     * @param couponQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Coupon>> listCouponByPage(@RequestBody CouponQueryRequest couponQueryRequest) {
        long current = couponQueryRequest.getCurrent();
        long size = couponQueryRequest.getPageSize();
        // 查询数据库
        Page<Coupon> couponPage = couponService.page(new Page<>(current, size),
                couponService.getQueryWrapper(couponQueryRequest));
        return ResultUtils.success(couponPage);
    }

    /**
     * 分页获取优惠券列表（封装类）
     *
     * @param couponQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CouponVO>> listCouponVOByPage(@RequestBody CouponQueryRequest couponQueryRequest,
                                                               HttpServletRequest request) {
        long current = couponQueryRequest.getCurrent();
        long size = couponQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Coupon> couponPage = couponService.page(new Page<>(current, size),
                couponService.getQueryWrapper(couponQueryRequest));
        // 获取封装类
        return ResultUtils.success(couponService.getCouponVOPage(couponPage, request));
    }

    /**
     * 分页获取用户可购买优惠券关联表列表
     */
    @GetMapping("/list/canBuy")
    public BaseResponse<Page<CouponVO>> listCanBuyCoupon(
            @RequestParam(required = false) Long userId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long pageSize,
            HttpServletRequest request
    ) {
        // 限制爬虫
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        // 如果不是管理员，默认为当前用户
        if (!userService.isAdmin(request)) {
            userId = userService.getLoginUser(request).getId();
        }
        if (userId == null){
            userId = userService.getLoginUser(request).getId();
        }
        Page<CouponVO> userCouponPage =couponService.getListCanBuyCoupon(userId, current, pageSize);
        // 获取封装类
        return ResultUtils.success(userCouponPage);
    }

    /**
     * 获取秒杀券列表
     */
    @GetMapping("/list/seckillCoupon")
    public BaseResponse<Page<CouponVO>> listSeckillCoupon(
            @RequestParam(required = false) Long userId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long pageSize,
            HttpServletRequest request
    ) {
        // 如果不是管理员，默认为当前用户
        if (!userService.isAdmin(request)) {
            userId = userService.getLoginUser(request).getId();
        }
        if (userId == null){
            userId = userService.getLoginUser(request).getId();
        }
        Page<CouponVO> userCouponPage =couponService.getListSeckillCoupon(userId, current, pageSize);
        // 获取封装类
        return ResultUtils.success(userCouponPage);
    }

    // endregion
}
